<template>
  <div>
    <!-- 面包屑导航区域  -->
    <!-- - breadcurmb：面包屑
- separator-class：分隔样式
- to属性：是点击面包屑导航之后，跳转的链接 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryinfo.query"
            clearable
            @clear="getUserList"
          >
            <!-- - slot="append"，slot有插槽，还有位置的意思，这个属性的作用是：将button追加到input的后边
- 如果是slot="prepend"，那么就会将button放到input的前边 -->
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <!-- 表格区域  -->
      <!-- border设置纵向边框默认为true时：border=“true”可简写为border -->
      <!-- stripe设置隔行变色 -->
      <el-table :data="userlist" :border="true" :stripe="true">
        <!-- 增加索引列type=‘index’ -->
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- 监听switch切换事件,传递整行数据 -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userstateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="RemoveUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-share"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框弹出 -->
    <!-- sync修饰符介绍：一个组件需要提供多个双向绑定的属性时使用，
    只能选用一个属性来提供 v-model 功能，但如果有其他属性也要提供
    双向绑定，就需要.sync  -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addCloseDialog"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="EditdialogVisible"
      width="50%"
      @close="editCloseDialog"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="setRoledialogVisible"
      width="50%"
      @close="setRoleClose"
    >
      <div>
        <p>当前的用户：{{ userinfo.username }}</p>
        <p>当前的角色：{{ userinfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    // email邮箱验证
    // 参数rule为验证规则, value为需要验证的值,cb为回调函数
    var email = (rule, value, cb) => {
      const regemail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regemail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 手机号验证
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryinfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      dialogVisible: false,
      EditdialogVisible: false,
      setRoledialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editForm: {},
      userinfo: {},
      selectedRoleId: '',
      // 所有角色的列表数据
      rolesList: [],
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { required: true, message: '长度在 6 到 15 个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: email, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: email, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    // 更新数据方法
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryinfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    }, // 分页条目数改变事件
    handleSizeChange(val) {
      //   console.log(`每页 ${val} 条`)
      // 改变当前每页显示条目数
      this.queryinfo.pagesize = val
      //   重新调用getUserList()获取数据,刷新页面
      this.getUserList()
    }, // 分页页码值改变事件
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`)
      // 改变当前显示的页码值
      this.queryinfo.pagenum = val
      //   重新调用getUserList()获取数据,刷新页面
      this.getUserList()
    }, // 用户状态改变事件
    async userstateChange(val) {
      const { data: res } = await this.$http.put(
        `users/${val.id}/state/${val.mg_state}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新用户状态失败!')
      }
      this.$message.success('更新用户状态成功!')
      //   console.log(val)
    }, // 重置弹出框的数据
    addCloseDialog() {
      // this.$refs获取设置了ref的值为addFormRef的-dialog表单
      this.$refs.addFormRef.resetFields()
    }, // 表单预检验
    addUser() {
      // 获取表单数据 表单预检验
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)
        // 如果校验不符合,返回不进行下一步操作
        if (!valid) return
        // 成功所做操作
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加数据失败!')
        }
        this.$message.success('添加数据成功!')
        //   关闭对话框
        this.dialogVisible = false
        // 重新渲染数据
        this.getUserList()
      })
    }, // 修改弹出框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败！')
      }
      this.editForm = res.data
      //   console.log(this.editForm)
      this.EditdialogVisible = true
    },
    editCloseDialog() {
      this.$refs.editFormRef.resetFields()
    }, // 修改表单预校验
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改表单失败')
        //  关闭对话框
        this.EditdialogVisible = false
        //  更新数据
        this.getUserList()
        //  提示修改成功
        this.$message.success('修改表单成功')
      })
    }, // 删除按钮事件
    async RemoveUserById(id) {
      const removeResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) // 捕捉错误
      // console.log(removeResult) // confirm | cancel
      if (removeResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // 删除操作
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getUserList()
    }, // 分配角色事件
    async setRole(userinfo) {
      this.userinfo = userinfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表错误')
      }
      this.rolesList = res.data
      this.setRoledialogVisible = true
    }, // 分配用户角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('设置角色失败')
      }
      this.$message.success('设置角色成功')
      this.getUserList()
      this.setRoledialogVisible = false
    },
    setRoleClose() {
      this.userinfo = {}
      this.selectedRoleId = ''
    },
  },
}
</script>
<style lang="less" scoped>
p {
  margin: 20px auto;
}
</style>
